package fafmessenger.boundary;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import fafmessenger.control.InboxController;
import fafmessenger.entity.Response;

public class NewMessageGUI extends Activity {
	private InboxController inboxController;
	public ProgressDialog progressDialog;
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.newmessage);
	        
	        inboxController = new InboxController(this);
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setTitle("Please wait...");
	        progressDialog.setMessage("Sending message");
	        progressDialog.setIndeterminate(true);
	        progressDialog.setCancelable(false);
	        
	        final Button buttonSend = (Button) findViewById(R.id.sendbutton);
	        buttonSend.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					EditText editText = (EditText)findViewById(R.id.phonenumber);
					String toMobilenumber = editText.getText().toString();
					
					EditText editText2 = (EditText)findViewById(R.id.messagetext);
					String body = editText2.getText().toString();
					
					SendMessageThread thread = new SendMessageThread(toMobilenumber, body);	        	
		        	progressDialog.show();	        	
		        	thread.start();
				}
			});
	 }
	 
	 private class SendMessageThread extends Thread {
	    	
		 	private String mobilenumber;
	    	private String body;
	    	private Response r;
	    	
	    	public SendMessageThread(String mobilenumber, String body) {
	    		this.mobilenumber = mobilenumber;
	    		this.body = body;
	    	}
	    	
	    	@Override
	    	public void run() {
	    		r = inboxController.sendMessage(mobilenumber, body);      	
	        	handler.sendEmptyMessage(0);
	    	}
	    	
	    	private Handler handler = new Handler() {
	            @Override
	            public void handleMessage(android.os.Message msg) {
	            	progressDialog.dismiss();
	    			

	    			if (r == null){
		            	Toast toast = Toast.makeText(NewMessageGUI.this, "Unable to connect to server", 10);
		    			toast.show();
	    			}
	    			
	    			else {
		            	Toast toast = Toast.makeText(NewMessageGUI.this, r.getDescription(), 10);
		    			toast.show();
	    			}
	    			
					if (r != null && r.getResult() == true) {
						finish();
					}
	            }
	    	};
	    }
}
